import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../../app_files.dart';
import 'package:azlistview/azlistview.dart';
import 'package:shared_preferences/shared_preferences.dart';

Effect<UserTypeViewState> buildEffect() {
  return combineEffects(<Object, Effect<UserTypeViewState>>{
    UserTypeViewAction.action: _onAction,
    UserTypeViewAction.onSubmit: _onSubmit,
  });
}

void _onAction(Action action, Context<UserTypeViewState> ctx) {}

void _onSubmit(Action action, Context<UserTypeViewState> ctx) async {
  if (ctx.state.selectIndex == null) {
    CommonUtils.showErrorInfo(ctx.context, '请选择工作身份');
    return;
  }
  UserInfoEntity userInfo = GlobalStore.store.getState().userInfo;
  userInfo.currentRoleName = ctx.state.selectIndex;
  userInfo.isGsUser = false;
  GlobalStore.store.dispatch(GlobalActionCreator.onUserLogin(userInfo));
  CommonUtils.showWaitLoading(ctx.context);
  if (userInfo.isCheckWorker && ctx.state.isChanged) {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    int currentPlan =
        preferences.getInt(UserInfoConst.currentPlan + userInfo.userid) ?? 0;
    userInfo.currentPlan = currentPlan;
    ResultData plans = await CommonNetWork.staffCheckPlans();
    if (plans.success) {
      List list = plans.data['data'];
      userInfo.plans =
          list.map<PlanItemModel>((e) => PlanItemModel.fromJson(e)).toList();
      SuspensionUtil.sortListBySuspensionTag(userInfo.plans);
    }
  }

  if (userInfo.isPatrolWorker&& ctx.state.isChanged) {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    int currentPlan =
        preferences.getInt(UserInfoConst.currentPatrolPlan + userInfo.userid) ??
            0;
    userInfo.currentPatrolPlan = currentPlan;
    ResultData plans = await CommonNetWork.staffPatrolPlans();
    if (plans.success) {
      List list = plans.data['data'];
      userInfo.patrolPlans = list
          .map<PatrolPlanModel>((e) => PatrolPlanModel.fromJson(e))
          .toList();
      SuspensionUtil.sortListBySuspensionTag(userInfo.plans);
    }
  }
  Navigator.pop(ctx.context);
  if (ctx.state.isChanged)
    bus.emit('refreshMain');
  Navigator.pop(ctx.context);
}
